package cn.edu.ncut.cs.springboot.springsecuritydemo.service.impl;

import cn.edu.ncut.cs.springboot.springsecuritydemo.entity.Permission;
import cn.edu.ncut.cs.springboot.springsecuritydemo.repository.PermissionRepository;
import cn.edu.ncut.cs.springboot.springsecuritydemo.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionRepository permissionRepository;

    @Override
    public List<Permission> getAllPermissions() {
        return permissionRepository.findAll();  // 查询所有权限
    }

    @Override
    public Optional<Permission> getPermissionById(Long id) {
        return permissionRepository.findById(id);  // 根据 ID 查询权限
    }

    @Override
    public Permission createPermission(Permission permission) {
        return permissionRepository.save(permission);  // 保存新权限
    }

    @Override
    public Permission updatePermission(Long id, Permission permission) {
        if (permissionRepository.existsById(id)) {
            permission.setId(id);  // 确保更新的 ID 与数据库中一致
            return permissionRepository.save(permission);  // 更新权限
        }
        return null;  // 如果找不到该 ID，返回 null
    }

    @Override
    public boolean deletePermission(Long id) {
        if (permissionRepository.existsById(id)) {
            permissionRepository.deleteById(id);  // 删除权限
            System.out.println("Permission with ID " + id + " deleted.");
            return true;
        }
        System.out.println("Permission with ID " + id + " not found.");
        return false;
    }
}
